package online.heycm.platform.common.tools;

/**
 * 脱敏工具
 *
 * @author heycm
 * @since 2022/7/3 13:15
 */
public class SensitiveUtil {

    private static final char DESENSITIZED_CHAR = '*';

    private SensitiveUtil() {}

    /**
     * 字符串脱敏
     *
     * @param content 原字符串
     * @param left    左边保留字符个数
     * @param right   右边保留字符个数
     * @return
     */
    public static String hidden(String content, int left, int right) {
        assert content != null && left >= 0 && right >= 0;
        String[] split = content.split("");
        StringBuilder builder = new StringBuilder();
        int length = split.length;
        if (length <= (left + right)) {
            for (String s : split) {
                builder.append(DESENSITIZED_CHAR);
            }
            return builder.toString();
        }
        int strLength = length - right;
        for (int i = 0; i < left; i++) {
            builder.append(split[i]);
        }
        for (int i = left; i < strLength; i++) {
            builder.append(DESENSITIZED_CHAR);
        }
        for (int i = strLength; i < length; i++) {
            builder.append(split[i]);
        }
        return builder.toString();
    }

    /**
     * 18位身份证脱敏
     *
     * @param idCard 身份证
     * @return 10**************1X
     */
    public static String idCard18(String idCard) {
        return SensitiveUtil.hidden(idCard, 2, 2);
    }

    /**
     * 15位身份证脱敏
     *
     * @param idCard 身份证
     * @return 1*************X
     */
    public static String idCard15(String idCard) {
        return SensitiveUtil.hidden(idCard, 1, 1);
    }

    /**
     * 身份证脱敏
     *
     * @param idCard 身份证
     * @return
     */
    public static String idCard(String idCard) {
        assert idCard != null;
        return idCard.length() > 15 ? SensitiveUtil.idCard18(idCard) : SensitiveUtil.idCard15(idCard);
    }

    /**
     * 移动电话脱敏
     *
     * @param mobilePhone 手机号
     * @return 138********
     */
    public static String mobilePhone(String mobilePhone) {
        return SensitiveUtil.hidden(mobilePhone, 3, 0);
    }
}
